import cookieparser from "cookieparser"

export const state = () => ({})

export const getters = {}

export const mutations = {}

export const actions = {
  // store/index.js 初始化 vuex
  // 最先执行的生命周期
  // 只在服务端执行
  nuxtServerInit({ commit }, { req }) {
    let userInfo = {}
    let token = ""
    if (req.headers.cookie) {
      try{
        // 解析 cookie
        const data = cookieparser.parse(req.headers.cookie)
        if(data.token) {
          token = data.token
          data.userInfo && (userInfo = JSON.parse(data.userInfo))
        }

      }catch(error) {
        console.log(error)
      }

    }
    console.log("服务端初始化vuex", token, userInfo)
    console.log("nuxtServerInit 生命周期")
    commit("user/SET_USERINFO", userInfo)
    commit("user/SET_TOKEN", token)
  },
}
